using Senparc.Weixin.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
namespace Senparc.Weixin.HttpUtility
{
	public static class RequestUtility
	{
		public static string HttpGet(string url, Encoding encoding = null)
		{
			return new WebClient
			{
				Encoding = encoding ?? Encoding.UTF8
			}.DownloadString(url);
		}
		public static string HttpGet(string url, CookieContainer cookieContainer = null, Encoding encoding = null, int timeOut = 10000)
		{
			HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
			httpWebRequest.Method = "GET";
			httpWebRequest.Timeout = timeOut;
			if (cookieContainer != null)
			{
				httpWebRequest.CookieContainer = cookieContainer;
			}
			HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
			if (cookieContainer != null)
			{
				httpWebResponse.Cookies = cookieContainer.GetCookies(httpWebResponse.ResponseUri);
			}
			string result;
			using (Stream responseStream = httpWebResponse.GetResponseStream())
			{
				using (StreamReader streamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8")))
				{
					string text = streamReader.ReadToEnd();
					result = text;
				}
			}
			return result;
		}
		public static string HttpPost(string url, CookieContainer cookieContainer = null, Dictionary<string, string> formData = null, Encoding encoding = null, int timeOut = 10000)
		{
			MemoryStream memoryStream = new MemoryStream();
			formData.FillFormDataStream(memoryStream);
			return RequestUtility.HttpPost(url, cookieContainer, memoryStream, null, null, encoding, timeOut, false);
		}
		public static string HttpPost(string url, CookieContainer cookieContainer = null, Stream postStream = null, Dictionary<string, string> fileDictionary = null, string refererUrl = null, Encoding encoding = null, int timeOut = 10000, bool checkValidationResult = false)
		{
			HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
			httpWebRequest.Method = "POST";
			httpWebRequest.Timeout = timeOut;
			if (checkValidationResult)
			{
				ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RequestUtility.CheckValidationResult);
			}
			bool flag = fileDictionary != null && fileDictionary.Count > 0;
			if (flag)
			{
				postStream = (postStream ?? new MemoryStream());
				string text = "----" + DateTime.Now.Ticks.ToString("x");
				string format = "\r\n--" + text + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
				string format2 = "\r\n--" + text + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
				foreach (KeyValuePair<string, string> current in fileDictionary)
				{
					try
					{
						string value = current.Value;
						using (FileStream fileStream = FileHelper.GetFileStream(value))
						{
							string text2;
							if (fileStream != null)
							{
								text2 = string.Format(format, current.Key, Path.GetFileName(value));
							}
							else
							{
								text2 = string.Format(format2, current.Key, current.Value);
							}
							byte[] bytes = Encoding.UTF8.GetBytes((postStream.Length == 0L) ? text2.Substring(2, text2.Length - 2) : text2);
							postStream.Write(bytes, 0, bytes.Length);
							if (fileStream != null)
							{
								byte[] array = new byte[1024];
								int count;
								while ((count = fileStream.Read(array, 0, array.Length)) != 0)
								{
									postStream.Write(array, 0, count);
								}
							}
						}
					}
					catch (Exception ex)
					{
						throw ex;
					}
				}
				byte[] bytes2 = Encoding.UTF8.GetBytes("\r\n--" + text + "--\r\n");
				postStream.Write(bytes2, 0, bytes2.Length);
				httpWebRequest.ContentType = string.Format("multipart/form-data; boundary={0}", text);
			}
			else
			{
				httpWebRequest.ContentType = "application/x-www-form-urlencoded";
			}
			httpWebRequest.ContentLength = ((postStream != null) ? postStream.Length : 0L);
			httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
			httpWebRequest.KeepAlive = true;
			if (!string.IsNullOrEmpty(refererUrl))
			{
				httpWebRequest.Referer = refererUrl;
			}
			httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
			if (cookieContainer != null)
			{
				httpWebRequest.CookieContainer = cookieContainer;
			}
			if (postStream != null)
			{
				postStream.Position = 0L;
				Stream requestStream = httpWebRequest.GetRequestStream();
				byte[] array = new byte[1024];
				int count;
				while ((count = postStream.Read(array, 0, array.Length)) != 0)
				{
					requestStream.Write(array, 0, count);
				}
				postStream.Seek(0L, SeekOrigin.Begin);
				StreamReader streamReader = new StreamReader(postStream);
				string text3 = streamReader.ReadToEnd();
				postStream.Close();
			}
			HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
			if (cookieContainer != null)
			{
				httpWebResponse.Cookies = cookieContainer.GetCookies(httpWebResponse.ResponseUri);
			}
			string result;
			using (Stream responseStream = httpWebResponse.GetResponseStream())
			{
				using (StreamReader streamReader2 = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8")))
				{
					string text4 = streamReader2.ReadToEnd();
					result = text4;
				}
			}
			return result;
		}
		private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
		{
			return true;
		}
		public static bool IsWeixinClientRequest(this HttpContext httpContext)
		{
			return !string.IsNullOrEmpty(httpContext.Request.UserAgent) && httpContext.Request.UserAgent.Contains("MicroMessenger");
		}
		public static string GetQueryString(this Dictionary<string, string> formData)
		{
			string result;
			if (formData == null || formData.Count == 0)
			{
				result = "";
			}
			else
			{
				StringBuilder stringBuilder = new StringBuilder();
				int num = 0;
				foreach (KeyValuePair<string, string> current in formData)
				{
					num++;
					stringBuilder.AppendFormat("{0}={1}", current.Key, current.Value);
					if (num < formData.Count)
					{
						stringBuilder.Append("&");
					}
				}
				result = stringBuilder.ToString();
			}
			return result;
		}
		public static void FillFormDataStream(this Dictionary<string, string> formData, Stream stream)
		{
			string queryString = formData.GetQueryString();
			byte[] array = (formData == null) ? new byte[0] : Encoding.UTF8.GetBytes(queryString);
			stream.Write(array, 0, array.Length);
			stream.Seek(0L, SeekOrigin.Begin);
		}
		public static string HtmlEncode(this string html)
		{
			return System.Web.HttpUtility.HtmlEncode(html);
		}
		public static string HtmlDecode(this string html)
		{
			return System.Web.HttpUtility.HtmlDecode(html);
		}
		public static string UrlEncode(this string url)
		{
			return System.Web.HttpUtility.UrlEncode(url);
		}
		public static string UrlDecode(this string url)
		{
			return System.Web.HttpUtility.UrlDecode(url);
		}
	}
}
